package org.promote.hotspot.dashboard.netty;

import com.github.benmanes.caffeine.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.promote.hotspot.common.model.HotKeyModel;
import org.promote.hotspot.common.rule.KeyRule;
import org.promote.hotspot.dashboard.cache.CaffeineBuilder;
import org.promote.hotspot.dashboard.util.RuleUtil;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 此处存储所有发来的热key，统一处理入库
 *
 * @author enping.jep
 * @date 2024/02/21 16:13
 **/
@Slf4j
public class HotSpotReceiver {

    /**
     * 发来的热key集中营
     */
    private static LinkedBlockingQueue<HotKeyModel> hotKeyStoreQueue = new LinkedBlockingQueue<>();
    /**
     * 存储实时hotkey，供界面查询实时热key
     */
    private static Map<Integer, Cache<String, Object>> aliveKeyStore = new ConcurrentHashMap<>();

    public static void push(HotKeyModel model) {
        hotKeyStoreQueue.offer(model);
    }

    public static HotKeyModel take() {
        try {
            return hotKeyStoreQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostConstruct
    public void init() {
    }


    /**
     * 将热key存入本地缓存，设置过期时间
     */
    public static void writeToLocalCaffeine(HotKeyModel hotKeyModel) {
        String appNameKey = hotKeyModel.getAppName() + "/" + hotKeyModel.getKey();
        KeyRule keyRule = RuleUtil.findByKey(appNameKey);
        if (keyRule == null) {
            log.error("rule is null, hotkeyModel " + hotKeyModel.getAppName() + "-" + hotKeyModel.getKey());
            return;
        }
        Cache<String, Object> cache = aliveKeyStore.computeIfAbsent(keyRule.getDuration(), s -> CaffeineBuilder.cache(keyRule.getDuration()));
        cache.put(appNameKey, hotKeyModel);
    }
}
